package com.sss.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 *  gateway全局网关过滤器
 * @author sss
 * @date 2020-03-08 14:57
 **/
@Component
public class MyLogGateWayFilter implements GlobalFilter, Ordered {

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("************come in global过滤器"+new Date());
        ServerHttpResponse response = exchange.getResponse();
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (token==null) {
            tokenErrorResponse(response);
        }
        return chain.filter(exchange);
    }

    public int getOrder() {
        return 0;
    }

    private Mono<Void> tokenErrorResponse(ServerHttpResponse response ){
        JSONObject message = new JSONObject();
        message.put("code",4001);
        message.put("message","鉴权失败，无token或类型");
        byte[] bits = new byte[0];
        try {
            bits = message.toString().getBytes("utf8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "text/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
